home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5190 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.1 KB  |  67 lines

  1. Path: rain.fr!world-net!usenet
  2. From: Frederic LACHASSE <lachass@worldnet.fr>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Comparing Struct elements
  5. Date: Fri, 02 Feb 1996 22:14:34 +0000
  6. Organization: World-Net information exchange, Internet provider.
  7. Message-ID: <VA.00000018.00c6ba71@fred>
  8. References: <4eo1va$s6k@camelot.ccs.neu.edu>
  9. Reply-To: lachass@worldnet.fr
  10. NNTP-Posting-Host: client87.sct.fr
  11. X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
  12.  
  13. bhardwaj@ccs.neu.edu (saurabh bhardwaj) wrote:
  14. << I've been trying to compare structure elements using the if Statement.  Here
  15. is the code:
  16.  
  17.  
  18. double NumericVal(ClassRec& LetGrade){
  19.  
  20. cout << "assgning struct member usin . " << LetGrade.
  21. Grade << '\n';
  22. if(LetGrade.Grade == "A") return(4.000);
  23. else if(LetGrade.Grade == "A-") return(3.666);
  24. else if(LetGrade.Grade == "B+") return(3.333);
  25. else return 0;
  26. }
  27.  
  28. where LetGrade is the following struct:
  29.  
  30. struct ClassRec {
  31.      char Grade[3];
  32.      int   QH;
  33.      char Name[10];
  34.      };
  35.  
  36. I can't seem to compare the elements of the Grade[3] with "A" or "A-" or "B+"
  37. The function invariable returns 0.  I've also tried using the -> operator.  It
  38. doesn't work either!!!   Anyone know why???  I'll appreciate any help. >>
  39.  
  40. Your error is that operator == does not compare strings, it compares pointers 
  41. to char, so LetGrade.Grade evaluates to the pointer to the first character of 
  42. the LetGrade.Grade array and "A" evaluates to a pointer in static memory where 
  43. the compiler has stored the constant string. Obviously, the two have different 
  44. addresses, so the pointers are different.
  45.  
  46. To compare strings, you need to call a library functions. The standard one is 
  47. defined in string.h:
  48.  
  49.   int strcmp(const char *, const char *);
  50.  
  51. and returns -1 if the first string is before (alphabetical order) the second, 0 
  52. if they are identical and +1 otherwise.
  53.  
  54. Your test should be written:
  55.  
  56. if(strcmp(LetGrade.Grade, "A") == 0) return(4.000);
  57. else if(strcmp(LetGrade.Grade, "A-") == 0) return(3.666);
  58. else if(strcmp(LetGrade.Grade, "B+") == 0) return(3.333);
  59. else return 0;
  60.  
  61. I hope this'll help.
  62.  
  63.  Frederic LACHASSE (ECP 86)
  64.  CompuServe: 100530,2005
  65.  Internet: lachass@worldnet.fr
  66.  
  67.